const fs = require('fs');
const qs = require('querystring');
const multiparty = require('multiparty');
const CONFIG = require('./config');
const path = require('path')

// 单文件上传
function singleUpload(req, res) {
    /* 解析请求 */
    new multiparty.Form().parse(req, (err, fields, file) => {
        // 错误处理
        if (err) {
            console.log(err);
            res.statusCode = 400;
            return res.end(JSON.stringify({
                msg: '请求错误'
            }))
        }
        // 获取文件名和前缀
        let fileName = fields.fileName && fields.fileName[0];
        let suffix = fields.suffix && fields.suffix[0];
        // 写入
        let chunkPath = file.file[0].path;
        let filePath = path.resolve(__dirname, CONFIG.updateDir, fileName);

        let rs = fs.createReadStream(chunkPath);
        let ws = fs.createWriteStream(filePath);
        rs.pipe(ws);
        rs.on('end', () => {
            let imgSrc = `${CONFIG.host}:${CONFIG.port}/${CONFIG.updateDir}/${fileName}`;
            // 获取上传数据
            res.end(JSON.stringify({
                msg: '上传成功',
                imgSrc
            }))
        })
    })
}

// 多文件切片上传
function multicleUpload(req, res) {
    new multiparty.Form().parse(req, (err, fields, file) => {
        if (err) {
            res.statusCode = 400;
            res.end(JSON.stringify({
                msg: err
            }))
        }
        try {
            // 提取信息
            let { fileName, start } = JSON.parse(fields.fileInfo[0]);
            // 文件块
            let chunk = file.chunk[0];
            let end = start + chunk.size;
            // 文件路径
            let filePath = path.resolve(__dirname, CONFIG.uploadDir, fileName);
            // 创建IO流
            console.log(start, end);
            let ws;
            if (start == 0)
                ws = fs.createWriteStream(filePath, { flags: 'w' });//创建
            else
                ws = fs.createWriteStream(filePath, { flags: 'r+', start });//修改
            let rs = fs.createReadStream(chunk.path);
            rs.pipe(ws);
            rs.on('end', () => {
                res.end(JSON.stringify({
                    msg: 'ok',
                    imgSrc: `http://${CONFIG.uploadIP}:${CONFIG.port}/${CONFIG.uploadDir}/${fileName}`
                }))
            })
        } catch (err) {
            res.end(JSON.stringify({
                msg: err
            }))
        }
    })
}


module.exports = {
    singleUpload,
    multicleUpload
}